// 封装购物车Store模块
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './user'
import { _addNewCart, _getNewCartList, _delNewCart } from '@/apis/cart'
export const userCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)
  const cartList = ref([])
  // 获取最新购物车列表
  const updateCartNewList = async () => {
    const { data: res } = await _getNewCartList()
    cartList.value = res.result
  }
  const addCart = async (goods) => {
    // 判断是否登录
    const { skuId, count } = goods
    if (isLogin.value) {
      // 调用接口
      await _addNewCart({ skuId, count })
      await updateCartNewList()
    } else {
      // 添加购物车操作
      // 已添加过 count++
      // 未添加过 直接push
      // 通过匹配商品传递过来的数据对象中skuId是否存在cartList中，存在表明已添加过，不存在未添加过
      const item = cartList.value.find((item) => goods.skuId === item.skuId)
      if (item) {
        item.count++
      } else {
        cartList.value.push(goods)
      }
    }
  }
  // 删除商品数据
  const delCart = async (skuId) => {
    if (isLogin.value) {
      await _delNewCart([skuId])
      await updateCartNewList()
    }
    // 使用splice方法
    const index = cartList.value.findIndex(item => skuId === item.skuId)
    cartList.value.splice(index, 1)
  }
  // 清除购物车
  const clearCart = () => {
    cartList.value = []
  }
  // 计算属性
  // 1、总的数量、所有count之和
  const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
  // 2、总价=单价*数量
  const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
  // 全选商品方法
  const allCheck = (selected) => {
    // 把cartList中的每一项的selected都设置为当前的全选框状态
    cartList.value.forEach(item => item.selected = selected)
  }
  // 单选商品方法
  const singleCheck = (skuId, selected) => {
    const item = cartList.value.find(item => item.skuId === skuId)
    item.selected = selected
  }
  // 是否全选计算属性
  const isAll = computed(() => cartList.value.every((item) => item.selected))
  // 已选择数量
  const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
  // 已选择商品价钱合计
  const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0))
  return {
    cartList,
    allCount,
    allPrice,
    isAll,
    selectedCount,
    selectedPrice,
    allCheck,
    singleCheck,
    addCart,
    delCart,
    clearCart,
    updateCartNewList
  }
},
  {
    persist: true,
  })